package com.joizhang.seckill.mapper;

import com.joizhang.seckill.model.SecKillGoods;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Mapper
public interface SecKillGoodsMapper {

    @Select("select * from sk_goods_seckill where goods_id=#{goodsId}")
    SecKillGoods getSecKillGoodsByGoodsId(@Param("goodsId") long goodsId);

    @Select("<script>select * from sk_goods_seckill sg where goods_id in <foreach item='item' collection='goodsIds' open='(' separator=',' close=')'> #{item} </foreach></script>")
    List<SecKillGoods> getSecKillGoodsListByGoodsIds(@Param("goodsIds") List<Long> goodsIds);

    /**
     * 获取库存
     * @param goodsId
     * @return
     */
    @Select("select * from sk_goods_seckill where goods_id=#{goodsId}")
    int getStockByGoodsId(@Param("goodsId") long goodsId);

    /**
     * stock_count > 0 和 版本号实现乐观锁 防止超卖
     */
    @Update("update sk_goods_seckill set stock_count=stock_count-1, version=version+1 " +
            "where goods_id=#{goodsId} and stock_count > 0 and version=#{version}")
    int reduceStockByVersion(SecKillGoods seckillGoods);

    @Update("update sk_goods_seckill set stock_count=" +
            "case when stock_count>=1 then stock_count-1 else stock_count end" +
            "where goods_id=#{goodsId}")
    int reduceStock(SecKillGoods seckillGoods);

    /**
     * 获取最新版本号
     */
    @Select("select version from sk_goods_seckill where goods_id=#{goodsId}")
    int getVersionByGoodsId(@Param("goodsId") long goodsId);

}
